package com.cn.wanxi.util;


import java.io.*;
import java.util.List;

public class IOTool {
    private static File note;

    private static final String SPLIT = "\n";

    /**
     * 1.创建文件夹文件
     *
     * @return
     */
    public static void createNote(String path, String fileName) {
//        String path = "D:\\wanxi\\step-3\\canyin-03\\web\\note";
//        String fileName = "nav.txt";
        File navs = new File(path);
        if (!navs.exists()) {
            navs.mkdirs();    //创文件夹
        }
        File file = new File(path, fileName);
        try {
            file.createNewFile();  //创文件
        } catch (IOException e) {
            e.printStackTrace();
        }
        note = file;
    }

    /**
     * 写入数据
     * 把参数data（list集合的数据）写入到上一个方法返回的note（文件）中
     * @param data
     * @return
     */
    public static String writeData(List<String> data) {
        if (note == null || !note.exists()) {
            return "error";
        }
        try {
            OutputStream outputStream = new FileOutputStream(note);
            for (int i = 0; i < data.size(); i++) {
                outputStream.write(data.get(i).getBytes());
                outputStream.write(SPLIT.getBytes());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "success";
    }

    /**
     * 读取数据
     * @return
     */
    public static String readData() {
        if (note == null || !note.exists()) {
            return "error";
        }
        StringBuilder result = new StringBuilder();
        try {
            Reader reader = new FileReader(note);
            int read = 0;
            while ((read = reader.read()) != -1) {
                result.append((char) read);
            }
            System.out.println(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.toString();
    }
}
